package service

import (
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/gorm/logger"

	"gorm.io/gorm"

	// 引入数据库驱动
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
)

func initDB() (db *gorm.DB) {
	var err error
	var dsn string

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,  // Slow SQL threshold
			LogLevel:      logger.Error, // Log level
			Colorful:      true,         // Enable color
		},
	)
	gormConf := &gorm.Config{Logger: newLogger}

	switch Conf.Db.Use {
	case "sqlite":
		if _, err = os.Stat(Conf.Db.Sqlite.Path); os.IsNotExist(err) {
			log.Fatalf("数据库目录未找到: %v", err.Error())
		}
		dsn = Conf.Db.Sqlite.Path + Conf.Db.Sqlite.Name
		db, err = gorm.Open(sqlite.Open(dsn), gormConf)
	case "mysql":
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			Conf.Db.Mysql.User,
			Conf.Db.Mysql.Pass,
			Conf.Db.Mysql.Ip,
			Conf.Db.Mysql.Port,
			Conf.Db.Mysql.Db,
		)
		db, err = gorm.Open(mysql.Open(dsn),
			gormConf)
		if err == nil {
			s, _ := db.DB()
			s.SetMaxIdleConns(Conf.Db.Mysql.ConnMax)
			s.SetMaxOpenConns(Conf.Db.Mysql.ConnOpen)
		}

	default:
		log.Fatalf("没有找到数据库配置: %v", Conf.Db.Use)
	}
	if err != nil {
		log.Fatalf("数据连接失败: %v", err.Error())
	}
	Conf.Db.Dsn = dsn
	return
}
